<template>
  <view class="warehouse-container">
    <!-- 当前仓库信息 -->
    <view class="warehouse-info-section">
      <view class="warehouse-info-card">
        <view class="warehouse-icon">
          <text class="icon-text">🏭</text>
        </view>
        <view class="warehouse-content">
          <text class="warehouse-label">当前仓库</text>
          <text class="warehouse-name">{{ currentWarehouse.name }}</text>
        </view>

        <view class="card-item">
          <text class="number">{{ overview.totalWeight }} KG</text>
          <text class="label">当前库存</text>
        </view>
        <!-- <view class="card-item">
          <text class="number">{{ overview.totalAmount }} 万元</text>
          <text class="label">库存AA金额</text>
        </view> -->
        <view class="card-item">
          <text class="number">{{ overview.todayIn }} KG</text>
          <text class="label">今日入库</text>
        </view>
        <view class="card-item">
          <text class="number">{{ overview.todayOut }} KG</text>
          <text class="label">今日出库</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">数据加载中...</text>
    </view>

    <!-- 主要内容区域 -->
    <view class="content-wrapper">
      <!-- 仓库作业模块 -->
      <view class="operation-section">
        <view class="section-header">
          <text class="section-title">仓库作业</text>
          <text class="section-tag">核心功能</text>
        </view>

        <view class="operation-grid">
          <view
            v-for="menu in operationMenus"
            :key="menu.path"
            class="operation-item"
            :class="{ reverse: menu.path.includes('reverse') }"
            @tap="navigateTo(menu.path)"
          >
            <view class="operation-icon">
              <text class="icon-text">{{ menu.icon }}</text>
            </view>
            <view class="operation-content">
              <text class="operation-title">{{ menu.title }}</text>
              <text class="operation-desc">{{ menu.desc }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 记录查询模块 -->
      <view class="query-section">
        <view class="section-header">
          <text class="section-title">记录查询</text>
          <text class="section-tag">数据查询</text>
        </view>

        <view class="query-grid">
          <view
            v-for="menu in queryMenus"
            :key="menu.path"
            class="query-item"
            :class="{ reverse: menu.path.includes('reverse') }"
            @tap="navigateTo(menu.path)"
          >
            <view class="query-icon">
              <text class="icon-text">{{ menu.icon }}</text>
            </view>
            <view class="query-content">
              <text class="query-title">{{ menu.title }}</text>
              <text class="query-desc">{{ menu.desc }}</text>
              <view
                v-if="
                  (menu.path === 'in-record' && inRecordCount > 0) ||
                  (menu.path === 'out-record' && outRecordCount > 0)
                "
                class="record-badge"
              >
                {{ menu.path === "in-record" ? inRecordCount : outRecordCount }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import { inventoryApi } from "@/api/warehouse/inventory";

export default {
  data() {
    return {
      currentWarehouse: {
        id: 1,
        name: "原料仓库A",
      },
      overview: {
        totalWeight: 0,
        totalAmount: 0,
        todayIn: 0,
        todayOut: 0,
      },
      loading: false,
      // 记录统计数据
      inRecordCount: 12,
      outRecordCount: 8,
      // 静态菜单数组
      staticMenus: [
        // 仓库作业模块
        {
          matchTitle: "APP-标签打印",
          title: "标签打印",
          path: "label-print",
          icon: "🏷️",
          desc: "打印商品标签",
          type: "operation",
        },
        {
          matchTitle: "APP-入库作业",
          title: "入库作业",
          path: "stock-in",
          icon: "📥",
          desc: "商品入库登记管理",
          type: "operation",
        },
        {
          matchTitle: "APP-出库作业",
          title: "出库作业",
          path: "stock-out",
          icon: "📤",
          desc: "商品出库登记管理",
          type: "operation",
        },
        {
          matchTitle: "APP-入库红冲",
          title: "入库红冲",
          path: "reverse-in",
          icon: "↩️",
          desc: "入库单据冲销处理",
          type: "operation",
        },
        {
          matchTitle: "APP-出库红冲",
          title: "出库红冲",
          path: "reverse-out",
          icon: "↪️",
          desc: "出库单据冲销处理",
          type: "operation",
        },
        // 记录查询模块
        {
          matchTitle: "APP-入库记录",
          title: "入库记录",
          path: "in-record",
          icon: "📝",
          desc: "查看入库历史记录",
          type: "query",
        },
        {
          matchTitle: "APP-出库记录",
          title: "出库记录",
          path: "out-record",
          icon: "📋",
          desc: "查看出库历史记录",
          type: "query",
        },
        {
          matchTitle: "APP-库存查询",
          title: "库存查询",
          path: "stockReal-record",
          icon: "📊",
          desc: "实时库存数据查询",
          type: "query",
        },
        {
          matchTitle: "APP-入库红冲记录",
          title: "入库红冲记录",
          path: "reverse-in-record",
          icon: "🔄",
          desc: "查看入库红冲记录",
          type: "query",
        },
        {
          matchTitle: "APP-出库红冲记录",
          title: "出库红冲记录",
          path: "reverse-out-record",
          icon: "🔁",
          desc: "查看出库红冲记录",
          type: "query",
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["permissions", "menus"]),
    allowedMenus() {
      // 获取动态菜单数据，如果菜单不存在则默认空数组
      const dynamicMenus = this.menus || [];
      // 先筛选出动态菜单中的顶级菜单项（parentId=0）且name=APP-采购仓库作业
      const parentMenu = dynamicMenus.find(
        (dynamicMenu) =>
          dynamicMenu.parentId === 0 && dynamicMenu.name === "APP-采购仓库作业"
      ); // 如果没有找到父菜单，则返回空数组
      if (!parentMenu || !parentMenu.children) {
        return [];
      }
      // 获取父菜单的所有子节点
      // console.log("parentMenu.children", parentMenu.children);
      const childMenus = parentMenu.children || [];
      // 筛选出静态路由与动态路由子节点匹配的项，返回静态路由信息
      const filteredMenus = this.staticMenus.filter((staticMenu) =>
        childMenus.some((childMenu) => childMenu.name === staticMenu.matchTitle)
      );
      // console.log("filteredMenus", filteredMenus);
      return filteredMenus;
    },
    // 暴露filteredMenus供模板使用
    filteredMenus() {
      return this.allowedMenus;
    },
    // 分模块的菜单
    operationMenus() {
      return this.filteredMenus.filter((menu) => menu.type === "operation");
    },
    queryMenus() {
      return this.filteredMenus.filter((menu) => menu.type === "query");
    },
  },

  onLoad() {
    this.initWarehouseData();
    this.loadDashboardData();
  },

  methods: {
    async getCurrentWarehouse() {
      try {
        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.wmName,
          };
        }

        // 降级处理：尝试其他字段
        if (userConfig && userConfig.warehouseName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.warehouseName,
          };
        }
      } catch (error) {
        console.error("获取用户仓库失败:", error);
      }

      // 默认值
      return {
        warehouseId: "DEFAULT",
        warehouseName: "默认仓库",
      };
    },

    async initWarehouseData() {
      try {
        // 获取当前仓库信息
        const currentWarehouse = await this.getCurrentWarehouse();
        if (currentWarehouse && currentWarehouse.warehouseName) {
          this.currentWarehouse = {
            id: currentWarehouse.warehouseId,
            name: currentWarehouse.warehouseName,
          };
        }
      } catch (error) {
        console.error("获取仓库信息失败:", error);
      }
    },

    async loadDashboardData() {
      this.loading = true;
      try {
        // 获取当前仓库信息
        const currentWarehouse = await this.getCurrentWarehouse();
        const warehouseName = currentWarehouse.warehouseName;
        const today = new Date().toISOString().split("T")[0];

        // 确定real_type
        let realType = "原料";
        if (warehouseName.includes("五金")) {
          realType = "五金";
        } else if (warehouseName.includes("备件")) {
          realType = "备件";
        }

        // 并行获取所有数据
        const [stockRes, inRes, outRes] = await Promise.all([
          // inventoryApi.getStockAmount({
          //   realType,
          //   warehouseName,
          //   busStatus: "已入库",
          // }),
          // inventoryApi.getStockInAmount({
          //   warehouseName,
          //   busStatus: "已入库",
          //   ywDate: today,
          // }),
          // inventoryApi.getStockOutAmount({
          //   warehouseName,
          //   busStatus: "已出库",
          //   ywDate: today,
          // }),
        ]);

        // 更新数据
        this.overview = {
          // totalWeight: stockRes.prodCount || 0,
          // totalAmount: this.formatToWan(stockRes.sumAmount || 0),
          // todayIn: inRes.prodCount || 0,
          // todayOut: outRes.prodCount || 0,
          totalWeight: 0,
          totalAmount: 0,
          todayIn: 0,
          todayOut: 0,
        };
      } catch (error) {
        console.error("加载仪表盘数据失败:", error);
        uni.showToast({
          title: "数据加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    formatToWan(amount) {
      if (!amount) return 0;
      return (amount / 10000).toFixed(2);
    },

    navigateTo(type) {
      const routes = {
        // 仓库作业
        "stock-in": "/pages/smart/warehouse/in-warehouse/create",
        "stock-out": "/pages/smart/warehouse/out-warehouse/create",
        "stock-taking": "/pages/smart/warehouse/stock-taking/index",
        // 标签打印
        "label-print": "/pages/smart/warehouse/pdaPrint",
        "reverse-in": "/pages/smart/warehouse/reverse/inbound",
        "reverse-out": "/pages/smart/warehouse/reverse/outbound",
        // 记录查询
        "in-record": "/pages/smart/warehouse/report/stockIn",
        "out-record": "/pages/smart/warehouse/report/stockOut",
        inventory: "/pages/smart/warehouse/inventory/query",
        "taking-record": "/pages/smart/warehouse/report/taking",
        "reverse-in-record": "/pages/smart/warehouse/report/reverseIn",
        "reverse-out-record": "/pages/smart/warehouse/report/reverseOut",
        "stockReal-record": "/pages/smart/warehouse/report/stockReal",
        // 其他功能
        report: "/pages/smart/warehouse/report/index",
      };

      if (routes[type]) {
        uni.navigateTo({
          url: routes[type],
        });
      } else {
        uni.showToast({
          title: "功能开发中...",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/index.scss";
</style>
